#!/usr/bin/env python3
# losses/custom_losses.py

import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
import torchvision

class ResidualDenseBlock(nn.Module):
    """残差密集块，ESRGAN的核心组件"""
    def __init__(self, nf=64, gc=32, bias=True):
        super(ResidualDenseBlock, self).__init__()
        self.conv1 = nn.Conv2d(nf + 0 * gc, gc, 3, 1, 1, bias=bias)
        self.conv2 = nn.Conv2d(nf + 1 * gc, gc, 3, 1, 1, bias=bias)
        self.conv3 = nn.Conv2d(nf + 2 * gc, gc, 3, 1, 1, bias=bias)
        self.conv4 = nn.Conv2d(nf + 3 * gc, gc, 3, 1, 1, bias=bias)
        self.conv5 = nn.Conv2d(nf + 4 * gc, nf, 3, 1, 1, bias=bias)
        self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
        
        # 初始化权重
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')

    def forward(self, x):
        x1 = self.lrelu(self.conv1(x))
        x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
        x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
        x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
        # 残差连接
        return x5 * 0.2 + x

class RRDB(nn.Module):
    """残差在残差密集块"""
    def __init__(self, nf, gc=32):
        super(RRDB, self).__init__()
        self.rdb1 = ResidualDenseBlock(nf, gc)
        self.rdb2 = ResidualDenseBlock(nf, gc)
        self.rdb3 = ResidualDenseBlock(nf, gc)

    def forward(self, x):
        out = self.rdb1(x)
        out = self.rdb2(out)
        out = self.rdb3(out)
        # 残差连接
        return out * 0.2 + x

class ContentLoss(nn.Module):
    """内容损失函数，使用VGG特征提取器"""
    def __init__(self, device):
        super(ContentLoss, self).__init__()
        # 使用预训练的VGG作为特征提取器
        vgg = torchvision.models.vgg19(pretrained=True).features[:35].eval()
        for param in vgg.parameters():
            param.requires_grad = False
        self.vgg = vgg.to(device)
        self.criterion = nn.L1Loss()
        self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 
                                             std=[0.229, 0.224, 0.225])

    def forward(self, sr, hr):
        # 归一化输入以匹配VGG训练条件
        sr_norm = self.normalize(sr)
        hr_norm = self.normalize(hr)
        # 提取特征
        sr_feat = self.vgg(sr_norm)
        hr_feat = self.vgg(hr_norm)
        return self.criterion(sr_feat, hr_feat)
    
class GANLoss(nn.Module):
    """GAN损失函数"""
    def __init__(self, gan_type='vanilla', real_label_val=1.0, fake_label_val=0.0):
        super(GANLoss, self).__init__()
        self.gan_type = gan_type
        self.real_label_val = real_label_val
        self.fake_label_val = fake_label_val
        
        if self.gan_type == 'vanilla':
            self.loss = nn.BCEWithLogitsLoss()
        elif self.gan_type == 'lsgan':
            self.loss = nn.MSELoss()
        else:
            raise NotImplementedError(f"GAN type {self.gan_type} is not implemented")

    def forward(self, pred, target_is_real):
        if target_is_real:
            target_val = self.real_label_val
        else:
            target_val = self.fake_label_val
            
        target = torch.full_like(pred, fill_value=target_val, device=pred.device)
        return self.loss(pred, target)
    